package com.typing.battle.activity;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.OnEditorActionListener;


import com.typing.battle.value.FriendDTO;
import com.typing.battle.value.MessageDTO;
import com.typing.battle.value.ServerComunicationDTO;
import com.typing.battle.view.FriendListViewForChatRoom;
import com.typing.battle.view.FriendListViewForDefault;
import com.typing.battle.async.ImageAsync;
import com.typing.battle.listener.OnDataSyncCompleteListener;
import com.typing.battle.receiver.C2dmBroadcastReceiver;
import com.typing.battle.receiver.ServerPollingReceiver;
import com.typing.battle.service.ITypingBattlePollingService;
import com.typing.battle.service.TypingBattlePollingService;
import com.typing.battle.util.C2dmUtil;
import com.typing.battle.util.KLog;
import com.typing.battle.util.PreferenceMgr;
import com.typing.battle.util.ServerComunicationUtil;
import com.typing.battle.util.StrUtil;
import com.typing.battle.util.TypingSpeedCalculator;
import com.typing.battle.R;

public class TypingBattleChatRoomActivity extends TypingBattleRootActivity{
	public ServiceConnection conn=null;
	public static TypingBattleChatRoomActivity typingBattleActivity;
	private String _ID;
	private EditText msg_text;
	private Button msg_send, invite;
	private LinearLayout chatWindow;
	private ScrollView scroll;
	private String phoneNum;
	private PreferenceMgr mgr;
	private TypingSpeedCalculator calculator;
	private String sentenceId;
	private boolean isFirstKey = true;
	private boolean isLock = false;
	private boolean isChampion = false;

	private String orgStr = "";
	public final static int FRIEND_WINDOW = 0;

	public static final int MODE_CHATING = 0;
	public static final int MODE_TYPING = 1;

	public Context mContext;
	private int _MODE;
	private int scrollHeight = 470;
	private String battleSeq;
	
	private TextView clickedView;
	private boolean isExit = false;
	
	LinearLayout.LayoutParams sendParams,receiveParams ,notiParams;
	private OnClickListener nameClickListener = new OnClickListener(){

		@Override
		public void onClick(View arg0) {
			clickedView = (TextView)arg0;
			// TODO Auto-generated method stub
			DialogInterface.OnClickListener friendAddListener = new DialogInterface.OnClickListener() 
    	    { 
    	      @Override 
    	      public void onClick(DialogInterface dialog, int which) 
    	      { 
    	    	String email = clickedView.getText().toString();
    	        addFriend(email); 
    	      } 
    	    }; 
    	     
    	    DialogInterface.OnClickListener banishListener = new DialogInterface.OnClickListener() 
    	    { 
    	      @Override 
    	      public void onClick(DialogInterface dialog, int which) 
    	      { 
    	    	String email = clickedView.getText().toString();  
    	        banish(email); 
    	      } 
    	    }; 
    	     
    	    DialogInterface.OnClickListener cancelListener = new DialogInterface.OnClickListener() 
    	    { 
    	      @Override 
    	      public void onClick(DialogInterface dialog, int which) 
    	      { 
    	        dialog.dismiss(); 
    	      } 
    	    }; 
    	     
    	    new AlertDialog.Builder(mContext) 
    	      .setTitle("메뉴") 
    	      .setPositiveButton("친구추가", friendAddListener) 
    	      .setNeutralButton("강제퇴장", banishListener) 
    	      .setNegativeButton("취소", cancelListener) 
    	      .show(); 
		}
		
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.battle_chat_room);
		mgr = PreferenceMgr.getInstance(this);
		mContext = this;
		_ID = getIntent().getStringExtra("CHAT_ROOM_ID");
		isChampion = getIntent().getBooleanExtra("isChampion",false);
		
		if(getIntent().getBooleanExtra("isInvite", false)){
			NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
			
			nm.cancel(1234);
			ServerComunicationDTO dto1 = new ServerComunicationDTO();
			dto1.setActionType(ServerComunicationUtil.TYPE_CHAT_ROOM_MASTER_JOIN);
			dto1.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
			dto1.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
			dto1.setChatRoomId(_ID);
			try {
				ServerComunicationUtil.serverAction(dto1,this);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		chatWindow = (LinearLayout) findViewById(R.id.layout_chat_window);
		scroll = (ScrollView) findViewById(R.id.scroll_chat_window);
		
		typingBattleActivity = this;
		msg_text = (EditText) findViewById(R.id.input_message);
		msg_send = (Button) findViewById(R.id.btn_send_message);
		invite = (Button) findViewById(R.id.btn_invite_friend);
		
		sendParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
		sendParams.gravity = Gravity.RIGHT;
		sendParams.leftMargin = 100;
		sendParams.topMargin = 5;
		sendParams.bottomMargin = 5;
		
		receiveParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
		receiveParams.gravity = Gravity.LEFT;
		receiveParams.rightMargin = 100;
		receiveParams.topMargin = 5;
		receiveParams.bottomMargin = 5;
		
		notiParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
		notiParams.gravity = Gravity.CENTER;
		notiParams.bottomMargin = 10;
		
		msg_text.setOnLongClickListener(new OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View v) {
				// TODO Auto-generated method stub
				return true;
			}
		});
		msg_text.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub

				return false;
			}
		});
		msg_text.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				if (!isFirstKey) {
					isFirstKey = true;
					calculator = new TypingSpeedCalculator(orgStr);
				}
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				// Log.d("afterTextChanged",""+s);
			}
		});
		msg_text.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				   scroll.postDelayed( new Runnable(){

					    @Override
					    public void run() {
					     scroll.smoothScrollBy(0, chatWindow.getHeight());
					    }
					    
					   }, 100);     
			}
		});



		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		phoneNum = tm.getLine1Number();

		

		chatWindow.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {
					hideSoftKeyboard(v);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		scroll.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {
					hideSoftKeyboard(v);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		invite.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {
					showFriendList();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		msg_send.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				c2dmSend(getMode());
			}
		});
		/*conn=new ServiceConnection() {
			ITypingBattlePollingService mService;
        	@Override
        	public void onServiceConnected(ComponentName name, IBinder service){  
        		// TODO Auto-generated catch block
        		mService =  ITypingBattlePollingService.Stub.asInterface(service);
        		try {        			
        			
        			mService.startChatMessageSync(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""), _ID);       			
				} catch (RemoteException e) {					
					e.printStackTrace();
				}
        	}
        	@Override
        	public void onServiceDisconnected(ComponentName name){
        		// TODO Auto-generated catch block
        		if(mService == null) return;
        		try {        			
        			
        			mService.stopChatMessageSync();       			
				} catch (RemoteException e) {					
					e.printStackTrace();
				}
        	}			
        };
        bindService(new Intent(mContext,TypingBattlePollingService.class) ,conn, Context.BIND_AUTO_CREATE);
		*/
	}

	private void showFriendList() {
		Intent intent = new Intent(this, TypingBattleFriendListActivity.class);
		intent.putExtra(TypingBattleFriendListActivity.PARAMETER_NAME,
				TypingBattleFriendListActivity.TYPE_CHATROOM);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivityForResult(intent, FRIEND_WINDOW);
	}

	public void hideSoftKeyboard(View input) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(data == null) return;
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case FRIEND_WINDOW:
			ServerComunicationDTO dto = new ServerComunicationDTO();
			dto.setActionType(ServerComunicationUtil.TYPE_BATTLE_INVITE);
			dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
			dto.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
			dto.setSendType(ServerPollingReceiver.TYPE_INVITE);
			dto.setChatRoomId(_ID);
			//dto.setChatRoomName(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, "") + "&" + friendEmail);
	    	//dto.setChatRoomOwner(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
	    	//dto.setChatRoomType("9");
	    	//dto.setMaxPeopleCount("2");
			//dto.setFriendEmail(friendEmail);
			dto.setReceiveEmail(data.getStringExtra("friendEmail"));
			try {
				ServerComunicationUtil.serverAction(dto, mContext);
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		}
	}

	@Override
	public boolean onCreatePanelMenu(int featureId, Menu menu) {
		// TODO Auto-generated method stub
		menu.add("배틀시작");
		menu.add("방정보");
		return super.onCreatePanelMenu(featureId, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getTitle().equals("배틀시작")) {
			if (!isLock) {
				if(isChampion){
					ServerComunicationDTO dto = new ServerComunicationDTO();
					dto.setActionType(ServerComunicationUtil.TYPE_TYPING_START);
					dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_NULL);
					dto.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
					dto.setChatRoomId(_ID);
					dto.setSendType(C2dmBroadcastReceiver.TYPE_TYPING_START);
					// dto.setSeq(""+(battleSeq+1));
					dto.setMsg(msg_text.getText().toString());
					Log.d("배틀 시작","시작");
					try {
						ServerComunicationUtil.battleStart(dto, mContext);
					} catch (Exception e) {
						e.printStackTrace();
					}
					Log.d("배틀 시작","끝");
				}else{
					Toast toast = Toast.makeText(this, "승자만 배틀을 진행하실수 있습니다.",
							Toast.LENGTH_SHORT);
					toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
					toast.show();
				}
			} else {
				Toast toast = Toast.makeText(this, "배틀이 진행중입니다.",
						Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
				toast.show();
			}
		}else if(item.getTitle().equals("방정보")) {
			Intent intent = new Intent();
			intent.putExtra("chatRoomId", _ID);
			intent.setClass(this, TypingBattleChatRoomInfoActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed() {
		showConfirm(this, R.string.dialog_exit_msg, true, TYPE_ROOM_EXIT);
	}
	@Override
	public void dialogPositive(int type) {
		exitRoom();
		super.dialogPositive(type);
	}

	public void showNotify(int[] speed) {
		Toast toast = Toast.makeText(this, "타수 :" + speed[1] + "\n" + "정확도 :"
				+ speed[2], Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
		toast.show();
	}

	@Override
	protected void onDestroy() {
		
		
		KLog.d(this, "onDestroy",isExit);
		if(!isExit) exitRoom();
//		ServerComunicationDTO dto = new ServerComunicationDTO();
//		dto.setActionType(ServerComunicationUtil.TYPE_CHAT_ROOM_QUIT);
//		dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_NULL);
//		dto.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
//		dto.setChatRoomId(_ID);
//		try {
//			ServerComunicationUtil.serverAction(dto, this);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		//this.unbindService(conn);
		super.onDestroy();
	}

	public void c2dmSend(int mode) {
		msg_text = (EditText) findViewById(R.id.input_message);
		msg_send = (Button) findViewById(R.id.btn_send_message);
		switch (mode) {
		case MODE_TYPING:
			try {
				// 메시지를 보낼때 sender(발급받은 ID, 토큰인증값, 메시지)
				calculator.endTyping(msg_text.getText().toString());
				int[] result = calculator.calculate();
				Log.d("걸린시간", result[0] + "밀리세컨드");
				Log.d("타수", "" + result[1] + " 타  / 분");
				Log.d("정확도", "" + result[2] + "%");
				showNotify(result);
				calculator.reset();
				isFirstKey = true;
				Log.d("타이핑모드", "타이핑모드다");
				ServerComunicationDTO dto = new ServerComunicationDTO();
				dto.setActionType(ServerComunicationUtil.TYPE_SEND_SPEED);
				dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
				dto.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
				dto.setChatRoomId(_ID);
				dto.setTypingTime("" + result[0]);
				dto.setTypingSpeed("" + result[1]);
				dto.setTypingAccuracy("" + result[2]);
				dto.setSentenceId(sentenceId);
				dto.setSeq("" + battleSeq);
				dto.setSendType(C2dmBroadcastReceiver.TYPE_TYPING_RESULT);
				dto.setMsg(msg_text.getText().toString());
				try {
					ServerComunicationUtil.serverAction(dto, mContext);
				} catch (Exception e) {
					e.printStackTrace();
				}

				msg_text.setText("");
				setMode(MODE_CHATING);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case MODE_CHATING:
			try {
				Log.d("채팅모드", "채팅모드다");
				if(msg_text != null && !"".equals(msg_text.getText().toString().trim())){
					ServerComunicationDTO dto = new ServerComunicationDTO();
					dto.setActionType(ServerComunicationUtil.TYPE_SEND_MESSAGE);
					dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
					dto.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
					dto.setChatRoomId(_ID);
					dto.setSendType(C2dmBroadcastReceiver.TYPE_MESSAGE);
					dto.setMsg(msg_text.getText().toString());
					try {
						ServerComunicationUtil.serverAction(dto, mContext);
					} catch (Exception e) {
						e.printStackTrace();
					}
					MessageDTO message = new MessageDTO();
					message.setMsg(dto.getMsg());
					message.setSenderEmail(dto.getUserEmail());
					setSendMessage(message);
				}
				msg_text.setText("");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			break;
		}
	}

	public int getMode() {
		return _MODE;
	}

	public void setMode(int mode) {
		_MODE = mode;
	}

	public void startTyping(String str, String id, String seq) {
		isLock = true;
		isFirstKey = false;
		this.orgStr = str;
		this.sentenceId = id;
		calculator = new TypingSpeedCalculator(str);
		// calculator.setOriginalStr(str);
		this.battleSeq = seq;
		setMode(MODE_TYPING);

	}

	public void endTyping() {
		isLock = false;
		isFirstKey = true;
		this.orgStr = "";
		this.sentenceId = "";
		setMode(MODE_CHATING);
	}
	public void setSendMessage(MessageDTO dto){
		TextView chatName = new TextView(this);
		TextView chatMessage = new TextView(this);
		chatName.setText(dto.getSenderEmail());
		chatMessage.setText(dto.getMsg());

		chatName.setGravity(Gravity.RIGHT);
		chatMessage.setGravity(Gravity.LEFT);

		chatName.setTextSize(10);
		chatMessage.setTextSize(16);
		chatMessage.setTextColor(Color.BLACK);
		chatMessage.setBackgroundResource(R.drawable.to_bubble);
		chatMessage.setPadding(10, 7, 25, 5);
//		chatWindow.addView(chatName);
		chatWindow.addView(chatMessage,sendParams);
		scroll.post(new Runnable() {
		    @Override
		    public void run() {
//		    	scroll.smoothScrollTo(0, scrollHeight+=scrollHeight);
		    	scroll.smoothScrollTo(0, chatWindow.getHeight());
		    }

		});
	}
	
	public void setReceiveMessage(MessageDTO dto) {
		if(dto==null) return;
		KLog.d(this, "Receiver Type ====>>>"+dto.getType());
		switch (dto.getType()) {
		case C2dmBroadcastReceiver.TYPE_MESSAGE: {
				LinearLayout mainLayout = new LinearLayout(this);
				LinearLayout textLayout = new LinearLayout(this);
				ImageView vImg = new ImageView(this);
				TextView chatName = new TextView(this);
				TextView chatMessage = new TextView(this);
				
				vImg.setScaleType(ScaleType.FIT_XY);
				mainLayout.setOrientation(LinearLayout.HORIZONTAL);
				textLayout.setOrientation(LinearLayout.VERTICAL);
				
//		        vImg.setImageBitmap(getProfileImage(dto.getSenderEmail()));
		        ImageAsync sync= new ImageAsync(mContext, "http://www.typoong.com/upload/"+dto.getSenderEmail()+"_image.jpg", vImg);
				chatName.setText(StrUtil.getStr(dto.getSenderName()));
				chatMessage.setText(StrUtil.getStr(dto.getMsg()));
	
				chatName.setGravity(Gravity.LEFT);
				chatMessage.setGravity(Gravity.LEFT);
	
				chatName.setTextSize(10);
				chatMessage.setTextSize(16);
	
				chatName.setPadding(15, 0, 0, 0);
				chatMessage.setTextColor(Color.BLACK);
				chatName.setTextColor(Color.BLACK);
				chatMessage.setBackgroundResource(R.drawable.from_bubble);
				chatMessage.setPadding(20, 7, 15, 5);
				textLayout.addView(chatName);
				textLayout.addView(chatMessage,receiveParams);
				mainLayout.addView(vImg,60,60);
				mainLayout.addView(textLayout);
				chatWindow.addView(mainLayout);
//				chatWindow.addView(chatName);
//				chatWindow.addView(chatMessage,receiveParams);				
				
				chatName.setOnClickListener(nameClickListener);
			}
			break;
		case C2dmBroadcastReceiver.TYPE_NOTIFY:
			break;

		case C2dmBroadcastReceiver.TYPE_INVITE:
			break;

		case C2dmBroadcastReceiver.TYPE_ROOM_IN:
		case C2dmBroadcastReceiver.TYPE_ROOM_OUT:
			TextView chatNotice = new TextView(this);
			chatNotice.setGravity(Gravity.CENTER);
			chatNotice.setTextSize(14);
			chatNotice.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
			chatNotice.setTextColor(Color.WHITE);
			chatNotice.setBackgroundResource(R.drawable.enter_or_leave_bubble);
			chatNotice.setText(dto.getMsg());
			chatWindow.addView(chatNotice,notiParams);
			break;
		case C2dmBroadcastReceiver.TYPE_ROOM_BANISH :{
				
				TextView chatMessage = new TextView(this);
	
				
				chatMessage.setText(dto.getMsg());
	
				
				chatMessage.setGravity(Gravity.CENTER);
	
				
				chatMessage.setTextSize(20);
	
				
				chatWindow.addView(chatMessage);
			}
			break;	
		case C2dmBroadcastReceiver.TYPE_TYPING_START: {
				LinearLayout mainLayout = new LinearLayout(this);
				TextView chatName = new TextView(this);
				TextView chatMessage = new TextView(this);
				mainLayout.setOrientation(LinearLayout.VERTICAL);
				chatName.setText("**Strat Typing**");
				chatMessage.setText(dto.getMsg() + "\n");
	
				chatName.setGravity(Gravity.CENTER);
				chatMessage.setGravity(Gravity.CENTER);
	
				mainLayout.setBackgroundResource(R.drawable.status_bubble);
				mainLayout.setPadding(0, 0, 0, 5);
				chatName.setTextSize(15);
				chatMessage.setTextSize(16);
				chatMessage.setTextColor(Color.WHITE);
				mainLayout.addView(chatName);
				mainLayout.addView(chatMessage);
				chatWindow.addView(mainLayout,notiParams);
				//vibrator 
			    Vibrator vibrator = (Vibrator)this.getSystemService(Context.VIBRATOR_SERVICE);
			    vibrator.vibrate(300);
			}
			break;
		case C2dmBroadcastReceiver.TYPE_TYPING_END:
			break;
			

		case C2dmBroadcastReceiver.TYPE_TYPING_RESULT: {
			LinearLayout mainLayout = new LinearLayout(this);
			TextView chatName = new TextView(this);
			TextView chatMessage = new TextView(this);
			mainLayout.setOrientation(LinearLayout.VERTICAL);
			chatName.setText("**Typing Result**");
			chatMessage.setText(dto.getMsg());
			if(dto.getMsg() != null && !"".equals(dto.getMsg().trim() )){
				if(dto.getMsg().startsWith(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""))){
					isChampion = true;
				}else{
					isChampion = false;
				}
			}
			chatName.setGravity(Gravity.CENTER);
			chatMessage.setGravity(Gravity.CENTER);

			mainLayout.setBackgroundResource(R.drawable.enter_or_leave_bubble);
			mainLayout.setPadding(0, 0, 0, 5);
			chatName.setTextSize(15);
			chatMessage.setTextSize(16);
			chatMessage.setTextColor(Color.WHITE);
			mainLayout.addView(chatName);
			mainLayout.addView(chatMessage);
			chatWindow.addView(mainLayout,notiParams);
	
			}
			break;
		}
		scroll.post(new Runnable() {
		    @Override
		    public void run() {
//		    	scroll.smoothScrollTo(0, scrollHeight+=scrollHeight);
		    	scroll.smoothScrollTo(0, chatWindow.getHeight());
		    }

		});
		//scroll.smoothScrollTo(scroll.getScrollX(), chatWindow.getHeight());
	}
	
	private void addFriend(String email){
		ServerComunicationDTO dto = new ServerComunicationDTO();
		dto.setActionType(ServerComunicationUtil.TYPE_FRIEND_INSERT);
		dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
		dto.setFriendEmail(email);
    	dto.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));   
		
		try{
			ServerComunicationUtil.serverAction(dto, mContext,this);
		}catch(Exception e){
			Log.e("", "TYPE_FRIEND_INSERT ERROR ::: "+e.getMessage());
		}
	}
	
	private void banish(String email){
		ServerComunicationDTO dto = new ServerComunicationDTO();
		dto.setActionType(ServerComunicationUtil.TYPE_CHAT_ROOM_BANISH);
		dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
		dto.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
		
		dto.setChatRoomId(_ID);
		dto.setSendType(C2dmBroadcastReceiver.TYPE_ROOM_BANISH);
		dto.setMsg(email);
		try {
			ServerComunicationUtil.serverAction(dto, mContext);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void exitRoom(){
		KLog.d(this, "exitRoom",isExit);
		ServerComunicationDTO dto = new ServerComunicationDTO();
		dto.setActionType(ServerComunicationUtil.TYPE_CHAT_ROOM_QUIT);
		dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_NULL);
		dto.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
		dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
		dto.setChatRoomId(_ID);
		try {
			ServerComunicationUtil.serverAction(dto, this,this);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void onSyncComplete(int resultCode, ServerComunicationDTO dto, Object resultObj) {
		if(resultCode == OnDataSyncCompleteListener.RESULT_SYNC_FAIL){
			if(resultObj!=null)
				ServerComunicationUtil.showNotify((String)resultObj, this);
		}else{
			if(dto.getActionType() == ServerComunicationUtil.TYPE_FRIEND_INSERT){
				String result = null;
				try{
					result = (String)resultObj;
					if("NOT MEMBER".equals(result)){
						Toast toast = Toast.makeText(mContext, "회원이 아닙니다." ,Toast.LENGTH_SHORT);
						toast.show();
					}else if("ALREADY FRIEND".equals(result)){
						Toast toast = Toast.makeText(mContext, "이미 친구입니다." ,Toast.LENGTH_SHORT);
						toast.show();
					}else{
						KLog.d(this,"json",result);
						JSONObject obj = new JSONObject(result);
						Intent intent = new Intent(mContext, TypingBattleFriendListActivity.class);
						intent.putExtra("friendEmail", obj.getString("userEmail"));
						intent.putExtra("friendName", obj.getString("userName"));
						intent.putExtra("friendPhoneNo", obj.getString("userPhoneNo"));
						setResult(TypingBattleFriendListActivity.CONTACT_PICKER,intent);
						//finish();
					}
				}catch(Exception e){
					
				}
			}else if(dto.getActionType() == ServerComunicationUtil.TYPE_CHAT_ROOM_QUIT){
				isExit = true;
				finish();
			}
		}
		super.onSyncComplete(resultCode, dto, resultObj);
	}
}